import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import Unocss from 'unocss/vite'
import path from 'path'
import AutoImport from 'unplugin-auto-import/vite'
import { PluginIcons, PluginPagePaths } from './build/plugins'
import removeNoMatch from 'vite-plugin-router-warn'
import simpleHtmlPlugin from 'vite-plugin-simple-html'
import { execSync } from 'child_process'
import * as process from 'process'
import * as fs from 'fs'

// https://vitejs.dev/config/
export default defineConfig(({ command, mode }) => {
  const viteEnv = loadEnv(mode, process.cwd())
  const isBuild = command === 'build'
  const { VITE_PROXY_TARGET, VITE_TITLE } = viteEnv

  if (isBuild) {
    fs.readFile('./public/version.json', 'utf8', (err, data) => {
      if (!err) {
        let obj
        try {
          obj = JSON.parse(data)
          obj.version = execSync('git rev-parse --short HEAD').toString().trim()
        } catch (error) {
          throw Error(error)
        }
        // 在 JSON 序列化成功才会去同步修改 version.json 文件内容
        if (obj) fs.writeFileSync('./public/version.json', JSON.stringify(obj))
        // 没有找到文件，抛出异常
      } else throw Error(err)
    })
  }

  return {
    plugins: [
      vue(),
      Unocss(),
      AutoImport({
        imports: ['vue', 'vue-router'],
        dts: 'src/auto-import.ts',
      }),
      PluginIcons(),
      PluginPagePaths(),
      removeNoMatch(),
      simpleHtmlPlugin({
        minify: isBuild,
        inject: {
          data: {
            title: VITE_TITLE,
          },
        },
      }),
    ],
    resolve: {
      alias: {
        '@': path.resolve(process.cwd(), 'src'),
        '~': path.resolve(process.cwd()),
      },
    },
    server: {
      proxy: {
        '/api': {
          target: "http://localhost:3100",
          changeOrigin: true,
        },
      },
    },
    build: {
      chunkSizeWarningLimit: 1024, // chunk 大小警告的限制（单位kb）
    },
  }
})
